package com.ma.admin.handler

import com.ma.admin.dao.TrainRepository
import com.ma.admin.model.Trips
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import xyz.erupt.annotation.`fun`.DataProxy
import xyz.erupt.core.exception.EruptWebApiRuntimeException

/**
 * 对车次操作时的数据校验
 *
 * @author yong
 * @date 2021/2/6 22:25
 */
@Component
class TripsDataProxy : DataProxy<Trips> {
    @Autowired
    lateinit var trainRepository: TrainRepository

    /**
     * 在修改数据前验证
     *
     * @param trips 车次
     * @author yong
     * @date 2021/2/6 23:02
     * @return void
     */
    override fun beforeUpdate(trips: Trips) { //获取对应列车所允许的最大座位数量
        val trainName = trips.tripsTrainName
        val train = trainRepository.findByTrainName(trainName).firstOrNull()?:return
        val trainSeatNum = train.trainSeatNum
        if (trips.tripsFirstSeatNum + trips.tripsSecondSeatNum > trainSeatNum) {
            throw EruptWebApiRuntimeException("一等座二等座数量之和大于列车能承载的数量！")
        }

        //车票数量不能小于0
        if (trips.tripsFirstSeatNum < 0 || trips.tripsSecondSeatNum < 0) {
            throw EruptWebApiRuntimeException("车票数量不能低于0")
        }
    }

    /**
     * 在插入数据前验证一等座二等座数量之和是否大于列车能承载的数量
     * 增加一条新记录删除标志初始为，依据情况初始为0或1
     * @param trips 车次
     * @author yong
     * @date 2021/2/6 23:03
     * @return void
     */
    override fun beforeAdd(trips: Trips) { //获取对应列车所允许的最大座位数量
        val trainName = trips.tripsTrainName
        val train = trainRepository.findByTrainName(trainName).firstOrNull()?:return
        val trainSeatNum = train.trainSeatNum
        if (trips.tripsFirstSeatNum + trips.tripsSecondSeatNum > trainSeatNum) {
            throw EruptWebApiRuntimeException("一等座二等座数量之和大于列车能承载的数量！")
        }

        //增加一条新记录删除标志初始为0
        trips.tripsDeleteFlag = (0)

        //车票数量不能小于0
        if (trips.tripsFirstSeatNum < 0 || trips.tripsSecondSeatNum < 0) {
            throw EruptWebApiRuntimeException("车票数量不能低于0")
        }
    }
}